import 'package:flutter/services.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:dio/dio.dart' as myDio;
import 'package:flutter/material.dart';
import 'package:material_collection_app/utils/dio_utils.dart';
import 'package:material_collection_app/utils/event_bus_util.dart';
import 'package:material_collection_app/utils/utils.dart';
import 'package:image_picker/image_picker.dart';
import 'package:material_collection_app/widget/common/date_select.dart';
import 'package:image_gallery_saver/image_gallery_saver.dart';

class AddUpdateMaterialDialog extends StatefulWidget {
  final String baseApi;
  final int orderId;
  final String type;
  final Map item;
  final onSubmit;

  AddUpdateMaterialDialog(
      {Key key,
      this.baseApi = 'enter/',
      this.orderId,
      this.type,
      this.item,
      this.onSubmit})
      : super(key: key);

  @override
  State<StatefulWidget> createState() => AddUpdateMaterialDialogState();
}

class AddUpdateMaterialDialogState extends State<AddUpdateMaterialDialog> {
  int materialTypeId;
  String materialTypeName;
  List uploadList = [];
  List locatUploadList = [];
  String validDate = '';
  String baseApi = 'enter/';
  String uploadVideoPath = '';
  String depName;
  List weightList = ['KG', 'g', '斤', '吨'];
  String weight = '';
  List measureList = ['毫米', '分米', '厘米', '米'];
  String measure = '';
  List denomList = ['分', '元', '角'];
  String denom = '';
  String original_value = null;

  final picker = ImagePicker();
  TextEditingController _nameController = new TextEditingController();
  TextEditingController _numController = new TextEditingController();
  TextEditingController _typesController = new TextEditingController();
  TextEditingController _unitController = new TextEditingController();
  TextEditingController _remarkController = new TextEditingController();
  TextEditingController _weightController = new TextEditingController();
  TextEditingController _lengthController = new TextEditingController();
  TextEditingController _denomController = new TextEditingController();
  TextEditingController _originalVauleController = new TextEditingController();

  var eventBus = new EventBus();

  @override
  void initState() {
    super.initState();
    setState(() {
      baseApi = widget.baseApi;
    });
    initEditData();
    // 监听物资分类选择
    eventBus.on("enter_mct", (parmas) {
      var p = parmas['select'];
      setState(() {
        materialTypeId = p['id'];
        materialTypeName = p['name'];
      });
    });
  }

  initEditData() {
    if (widget.type == 'edit') {
      List images = [];

      for (var item in widget.item['goods_imgs']) {
        images.add({'path': item, 'success': true});
      }

      var typeName = 'mtype';

      //区分来自于报废入库和设备更换入库
      if (widget.baseApi == 'scrap_enter/' ||
          widget.baseApi == 'allocate_enter/') {
        typeName = 'mtypes';
      }

      setState(() {
        materialTypeId = widget.item[typeName] != null
            ? widget.item[typeName]['goods_type_id']
            : null;
        materialTypeName = widget.item[typeName] != null
            ? widget.item[typeName]['type_name']
            : '请选择物资类型';
        uploadList = images;
        uploadVideoPath = widget.item['goods_video'] == null
            ? ''
            : widget.item['goods_video'];
        weight = widget.item['weight_unit'] == null
            ? ''
            : widget.item['weight_unit'];
        measure = widget.item['measure_unit'] == null
            ? ''
            : widget.item['measure_unit'];
        denom = widget.item['denomination_unit'] == null
            ? ''
            : widget.item['denomination_unit'];
        original_value = widget.item['original_value'] == null
            ? ''
            : widget.item['original_value'];
      });

      _nameController.text = widget.item['name'];
      _numController.text = widget.item['num'].toString();
      _typesController.text = widget.item['specification'];
      _unitController.text = widget.item['unit'];
      _remarkController.text = widget.item['remark'];
      validDate = widget.item['valid_time'];
      _weightController.text = widget.item['weight'];
      _lengthController.text = widget.item['length'];
      _denomController.text = widget.item['denomination'];
      _originalVauleController.text = widget.item['original_value'];
    }
  }

  // 添加物资
  _addMaterial() {
    int id = widget.orderId;
    var name = _nameController.text.trim();
    var typeId = materialTypeId;
    var num = _numController.text.trim();
    var types = _typesController.text.trim();
    var unit = _unitController.text.trim();
    var remark = _remarkController.text.trim();
    var weightVal = _weightController.text.trim();
    var len = _lengthController.text.trim();
    var denomVal = _denomController.text.trim();
    var original_value = _originalVauleController.text.trim();

    if (name.isEmpty) {
      Utils.showText(text: '请输入物资名称', align: Alignment(0, 0));
      return;
    }
    if (typeId == null) {
      Utils.showText(text: '请选择物资类型', align: Alignment(0, 0));
      return;
    }
    if (num.toString().isEmpty) {
      Utils.showText(text: '请输入物资数量', align: Alignment(0, 0));
      return;
    }

    if (types.isEmpty) {
      Utils.showText(text: '请输入规格/型号', align: Alignment(0, 0));
      return;
    }

    if (uploadList == null || uploadList.isEmpty) {
      Utils.showText(text: '请上传照片', align: Alignment(0, 0));
      return;
    }

    List images = [];

    for (var item in uploadList) {
      images.add(item['path']);
    }

    DioUtils.request("${baseApi}addMaterial",
        context: context,
        method: "POST",
        params: {
          'order_id': id,
          'name': name,
          'type_id': typeId,
          'num': num,
          'specification': types,
          'unit': unit,
          'remark': remark,
          'goods_imgs': images,
          'valid_time': validDate,
          'goods_video': uploadVideoPath,
          'weight': weightVal,
          'weight_unit': weight,
          'length': len,
          'measure_unit': measure,
          'denomination': denomVal,
          'denomination_unit': denom,
          'original_value': original_value
        }, onSuccess: (res) {
      Utils.showText(text: res['msg']);
      if (res['code'] == 1) {
        widget.onSubmit({'id': ''});
        Navigator.pop(context);
      }
    }, onError: (error) {});
  }

  // 编辑物资
  _editMaterial() {
    int id = widget.item['id'];
    var name = _nameController.text.trim();
    var typeId = materialTypeId;
    var num = _numController.text.trim();
    var types = _typesController.text.trim();
    var unit = _unitController.text.trim();
    var remark = _remarkController.text.trim();
    var weightVal = _weightController.text.trim();
    var len = _lengthController.text.trim();
    var denomVal = _denomController.text.trim();
    var originalValue = _originalVauleController.text.trim();

    if (name.isEmpty) {
      Utils.showText(text: '请输入物资名称', align: Alignment(0, 0));
      return;
    }
    if (typeId == null) {
      Utils.showText(text: '请选择物资类型', align: Alignment(0, 0));
      return;
    }
    if (num.toString().isEmpty) {
      Utils.showText(text: '请输入物资数量', align: Alignment(0, 0));
      return;
    }

    List images = [];

    for (var item in uploadList) {
      images.add(item['path']);
    }
    DioUtils.request("${baseApi}updMaterial",
        context: context,
        method: "POST",
        params: {
          'id': id,
          'name': name,
          'type_id': typeId,
          'num': num,
          'specification': types,
          'unit': unit,
          'remark': remark,
          'goods_imgs': images,
          'valid_time': validDate,
          'goods_video': uploadVideoPath,
          'weight': weightVal,
          'weight_unit': weight,
          'length': len,
          'measure_unit': measure,
          'denomination': denomVal,
          'denomination_unit': denom,
          'original_value': originalValue,
          'is_save': 1
        }, onSuccess: (res) {
      Utils.showText(text: res['msg']);
      if (res['code'] == 1) {
        widget.onSubmit({'id': ''});
        Navigator.pop(context);
      }
    }, onError: (error) {});
  }

  Widget _buildDialogHead(title) {
    return Container(
      height: 80.w,
      decoration: BoxDecoration(
          color: Utils.hexToColor('#F7F7F7'),
          borderRadius: BorderRadius.only(
              topLeft: Radius.circular(12.w), topRight: Radius.circular(12.w))),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: <Widget>[
          Container(
            margin: EdgeInsets.only(left: 31.w),
            child: Text(title,
                style: TextStyle(
                    color: Utils.hexToColor('#333333'),
                    fontSize: 16,
                    fontWeight: FontWeight.bold)),
          ),
          InkWell(
            onTap: () {
              Navigator.of(context).pop();
            },
            child: Container(
              padding: EdgeInsets.fromLTRB(30.w, 24.w, 30.w, 24.w),
              alignment: Alignment.topRight,
              child: Image.asset(
                'assets/dialog_close.png',
                width: 36.w,
              ),
            ),
          )
        ],
      ),
    );
  }

  Widget _buildInput(title, controller, [isNumber = false, maxLines = 1]) {
    return Container(
      margin: EdgeInsets.only(bottom: 20.h),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        crossAxisAlignment: CrossAxisAlignment.center,
        children: <Widget>[
          Container(
            width: 160.w,
            alignment: Alignment.centerRight,
            child: Text(
              title + '：',
              // textAlign: TextAlign.end,
              style:
                  TextStyle(color: Utils.hexToColor('#999999'), fontSize: 14),
            ),
          ),
          Container(
            width: 460.w,
            height: maxLines > 1 ? 200.h : 70.h,
            child: TextField(
              inputFormatters: [
                FilteringTextInputFormatter.allow(
                    RegExp(isNumber ? '[0-9.]' : '[^]')),
              ],
              maxLines: maxLines,
              controller: controller,
              style: TextStyle(fontSize: 14, color: Colors.black), //输入文本的样式
              decoration: InputDecoration(
                hintText: "请输入" + title,
                hintStyle: TextStyle(color: Color(0xFFC8C8D9), fontSize: 14),
                contentPadding: EdgeInsets.fromLTRB(21.w, 10, 21.w, 10),
                fillColor: Colors.white,
                filled: true,
                enabledBorder: OutlineInputBorder(
                  borderRadius: BorderRadius.all(
                    Radius.circular(8.w),
                  ),
                  borderSide: BorderSide(
                    color: Utils.hexToColor('#D4D4D4'),
                    width: 1,
                  ),
                ),
                focusedBorder: OutlineInputBorder(
                  borderSide: BorderSide(
                    color: Utils.hexToColor('#D4D4D4'),
                    width: 1,
                  ),
                  borderRadius: BorderRadius.all(
                    Radius.circular(8.w),
                  ),
                ),
              ),
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildDateSelect(title) {
    return Container(
      margin: EdgeInsets.only(bottom: 20.h),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: <Widget>[
          Container(
            width: 160.w,
            alignment: Alignment.centerRight,
            child: Text(
              title + '：',
              // textAlign: TextAlign.end,
              style:
                  TextStyle(color: Utils.hexToColor('#999999'), fontSize: 14),
            ),
          ),
          Container(
            width: 460.w,
            child: DateSelect(
              defaultDate: validDate,
              resetDate: () {
                setState(() {
                  validDate = '';
                });
              },
              onConfirm: (date) => {
                setState(() {
                  validDate = date;
                })
              },
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildSelectInput(title, value) {
    return Container(
      margin: EdgeInsets.only(bottom: 20.h),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: <Widget>[
          Container(
            width: 160.w,
            height: 40,
            alignment: Alignment.centerRight,
            child: Text(
              title + '：',
              style:
                  TextStyle(color: Utils.hexToColor('#999999'), fontSize: 14),
            ),
          ),
          GestureDetector(
            onTap: () {
              Navigator.pushNamed(context, "/material_type",
                  arguments: {'baseApi': widget.baseApi});
            },
            child: Container(
              width: 460.w,
              height: 40,
              alignment: Alignment.centerLeft,
              padding: EdgeInsets.symmetric(horizontal: 15.w),
              decoration: BoxDecoration(
                  borderRadius: BorderRadius.circular(4),
                  border:
                      Border.all(color: Utils.hexToColor('#D2D2D2'), width: 1)),
              child: Container(
                child: Text(value.toString(),
                    style: TextStyle(
                        color: Utils.hexToColor(
                            (materialTypeName == '请选择物资类型' ||
                                    materialTypeName == null)
                                ? '#CBCACF'
                                : '#0000000'),
                        fontSize: 14)),
              ),
            ),
          )
        ],
      ),
    );
  }

  // 拍照
  Future getPhoto() async {
    Navigator.of(context).pop();
    final pickedFile = await picker.getImage(source: ImageSource.camera);
    if (pickedFile != null) {
      await ImageGallerySaver.saveFile(pickedFile.path);
    }
    _upLoadImage(pickedFile, uploadList.length);
  }

  // 相册照片
  Future getImage() async {
    Navigator.of(context).pop();
    final pickedFile = await picker.getImage(source: ImageSource.gallery);
    _upLoadImage(pickedFile, uploadList.length);
  }

  //上传图片
  // index 如果图片上传失败，从本地列表删除图片
  _upLoadImage(PickedFile image, int index) async {
    if (image != null) {
      setState(() {
        uploadList.add({'path': '', 'success': false});
      });

      String path = image.path;
      var name = path.substring(path.lastIndexOf("/") + 1, path.length);
      int index = uploadList.length - 1;

      myDio.FormData formdata = myDio.FormData.fromMap(
          {"file": await myDio.MultipartFile.fromFile(path, filename: name)});

      DioUtils.request("Upload/uploadGoods",
          context: context, method: "POST", params: formdata, onSuccess: (res) {
        if (res['code'] == 1) {
          int locatLength = locatUploadList.length;
          int successIndex = index == locatLength ? locatLength : index;

          setState(() {
            uploadList[successIndex]['success'] = true;
            uploadList[successIndex]['path'] = res['data']['path'];
            // uploadList.add(res['data']['path']);
          });
        } else {
          setState(() {
            uploadList.removeAt(index);
          });
          Utils.showText(text: res['msg']);
        }
      }, onError: (error) {});
    }
  }

  // 录制视频
  Future getVideo() async {
    final pickedFile = await picker.getVideo(source: ImageSource.camera);
    _uploadVideo(pickedFile);
  }

  //上传视频
  _uploadVideo(PickedFile image) async {
    if (image != null) {
      String path = image.path;
      print(path);
      var name = path.substring(path.lastIndexOf("/") + 1, path.length);

      myDio.FormData formdata = myDio.FormData.fromMap(
          {"file": await myDio.MultipartFile.fromFile(path, filename: name)});

      setState(() {
        uploadVideoPath = 'loading';
      });

      DioUtils.request("Upload/uploadGoods",
          context: context, method: "POST", params: formdata, onSuccess: (res) {
        if (res['code'] == 1) {
          setState(() {
            uploadVideoPath = res['data']['path'];
          });
        } else {
          setState(() {
            uploadVideoPath = '';
          });
          Utils.showText(text: res['msg']);
        }
      }, onError: (error) {});
    }
  }

  // 删除图片
  _removeImage(int index) {
    Utils.openAlert('确定要删除吗？', context).then((confirm) => {
          if (confirm)
            {
              setState(() {
                uploadList.removeAt(index);
                // locatUploadList.removeAt(index);
              })
            }
        });
  }

  _removeVideo() {
    Utils.openAlert('确定要删除吗？', context).then((confirm) => {
          if (confirm)
            {
              setState(() {
                uploadVideoPath = '';
              })
            }
        });
  }

  // 图片列表
  Widget _buildImageList(type) {
    List<Widget> widget = [];
    List<String> imgList = [];

    for (int i = 0; i < uploadList.length; i++) {
      var item = uploadList[i];
      var src = DioUtils.API_PREFIX + item['path'];

      imgList.add(src);

      widget.add(Container(
          decoration: BoxDecoration(
            color: Utils.hexToColor('#F1F3F4'),
            borderRadius: BorderRadius.all(Radius.circular(8.w)),
          ),
          child: Stack(children: <Widget>[
            GestureDetector(
              onTap: () {
                Navigator.pushNamed(context, "/photo_view",
                    arguments: {'list': imgList, 'index': i});
              },
              child: ClipRRect(
                borderRadius: BorderRadius.all(Radius.circular(8.w)),
                child: Image.network(src,
                    fit: BoxFit.cover, width: 136.w, height: 136.w),
              ),
            ),
            Positioned(
                top: 96.w,
                child: GestureDetector(
                    onTap: () {
                      if (item['success']) {
                        _removeImage(i);
                      }
                    },
                    child: Container(
                        width: 136.w,
                        height: 40.w,
                        alignment: Alignment.center,
                        decoration: BoxDecoration(
                          color: Color.fromRGBO(0, 0, 0, 0.4),
                          borderRadius: BorderRadius.vertical(
                              bottom: Radius.elliptical(8.w, 8.w)),
                        ),
                        child: Text(
                            item['success'] == false ? '上传中...' : '删除图片',
                            style:
                                TextStyle(color: Colors.white, fontSize: 10)))))
          ])));
    }

    widget.add(Container(
        child: InkWell(
      onTap: () {
        if (type == 'image') {
          selectImage();
        } else {
          getVideo();
        }
      },
      child: Image.asset('assets/add_img.png', width: 136.w, height: 136.w),
    )));

    return Wrap(spacing: 25.w, runSpacing: 25.w, children: widget);
  }

  Widget _buildImageBox(type) {
    String name = type == 'image' ? '图片' : '视频';

    return Container(
        margin: EdgeInsets.only(bottom: 20.h),
        child: Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            crossAxisAlignment: CrossAxisAlignment.start,
            children: <Widget>[
              Container(
                width: 160.w,
                margin: EdgeInsets.only(top: 20.w),
                alignment: Alignment.centerRight,
                child: Text(
                  '${name}：',
                  // textAlign: TextAlign.end,
                  style: TextStyle(
                      color: Utils.hexToColor('#999999'), fontSize: 14),
                ),
              ),
              Container(
                width: 460.w,
                child:
                    type == 'image' ? _buildImageList(type) : _buildVideoList(),
              )
            ]));
  }

  _buildVideoList() {
    return Container(
      child: Row(
        children: <Widget>[
          Offstage(
              offstage: uploadVideoPath != '' ? false : true,
              child: GestureDetector(
                onTap: () {
                  if (uploadVideoPath != '' && uploadVideoPath != 'loading') {
                    Navigator.pushNamed(context, "/video_play",
                        arguments: {'video_url': uploadVideoPath});
                  }
                },
                child: Container(
                  width: 136.w,
                  height: 136.w,
                  margin: EdgeInsets.only(right: 25.w),
                  decoration: BoxDecoration(
                      color: Utils.hexToColor('#eeeeee'),
                      borderRadius: BorderRadius.all(Radius.circular(3))),
                  // child: Image.asset('assets/video.png', width: 136.w,height: 136.w),
                  child: Stack(
                    children: <Widget>[
                      Image.asset('assets/video.png',
                          width: 136.w, height: 136.w),
                      Positioned(
                          top: 96.w,
                          child: GestureDetector(
                              onTap: () {
                                if (uploadVideoPath != '') {
                                  _removeVideo();
                                }
                              },
                              child: Container(
                                  width: 136.w,
                                  height: 40.w,
                                  alignment: Alignment.center,
                                  decoration: BoxDecoration(
                                    color: Color.fromRGBO(0, 0, 0, 0.4),
                                    borderRadius: BorderRadius.vertical(
                                        bottom: Radius.elliptical(8.w, 8.w)),
                                  ),
                                  child: Text(
                                      uploadVideoPath == 'loading'
                                          ? '上传中...'
                                          : '删除视频',
                                      style: TextStyle(
                                          color: Colors.white, fontSize: 10)))))
                    ],
                  ),
                ),
              )),
          Offstage(
            offstage: uploadVideoPath == '' ? false : true,
            child: Container(
                child: InkWell(
              onTap: () {
                getVideo();
              },
              child: Image.asset('assets/add_img.png',
                  width: 136.w, height: 136.w),
            )),
          )
        ],
      ),
    );
  }

  selectImage() {
    showModalBottomSheet(
      context: context,
      barrierColor: Color.fromRGBO(0, 0, 0, 0.2),
      backgroundColor: Colors.transparent,
      builder: (BuildContext context) {
        return Container(
          height: 370.w,
          child: Column(
            children: <Widget>[
              Container(
                width: 700.w,
                height: 100.w,
                child: ElevatedButton(
                  onPressed: getPhoto,
                  child: Text(
                    '拍照',
                    style: TextStyle(
                        color: Utils.hexToColor('#297CFF'),
                        fontWeight: FontWeight.w500),
                  ),
                  style: ElevatedButton.styleFrom(
                    backgroundColor: Colors.white,
                    shape: RoundedRectangleBorder(
                        borderRadius:
                            BorderRadius.vertical(top: Radius.circular(12.w))),
                  ),
                ),
              ),
              Container(
                width: 700.w,
                height: 1.w,
                color: Utils.hexToColor('#E6E6E6'),
              ),
              Container(
                width: 700.w,
                height: 100.w,
                child: ElevatedButton(
                  onPressed: getImage,
                  child: Text(
                    '我的相册',
                    style: TextStyle(
                        color: Utils.hexToColor('#297CFF'),
                        fontWeight: FontWeight.w500),
                  ),
                  style: ElevatedButton.styleFrom(
                    backgroundColor: Colors.white,
                    shape: RoundedRectangleBorder(
                        borderRadius: BorderRadius.vertical(
                            bottom: Radius.circular(12.w))),
                  ),
                ),
              ),
              Container(
                width: 700.w,
                height: 100.w,
                margin: EdgeInsets.only(top: 20.w),
                child: ElevatedButton(
                  onPressed: () {
                    Navigator.of(context).pop();
                  },
                  child: Text(
                    '取消',
                    style: TextStyle(
                        color: Utils.hexToColor('#999999'),
                        fontWeight: FontWeight.w500),
                  ),
                  style: ElevatedButton.styleFrom(
                    backgroundColor: Colors.white,
                    shape: RoundedRectangleBorder(
                        borderRadius: BorderRadius.circular(12.w)),
                  ),
                ),
              )
            ],
          ),
        );
      },
    );
  }

  Widget _buildSelectBox(title, list, BuildContext context, type) {
    return Container(
      margin: EdgeInsets.only(bottom: 20.h),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        crossAxisAlignment: CrossAxisAlignment.center,
        children: <Widget>[
          Container(
            width: 160.w,
            alignment: Alignment.centerRight,
            child: Text(
              title + '：',
              style:
                  TextStyle(color: Utils.hexToColor('#999999'), fontSize: 14),
            ),
          ),
          Container(
              width: 460.w,
              child: GestureDetector(
                  onTap: () {
                    showModalBottomSheet(
                        context: context,
                        builder: (BuildContext context) {
                          return new Container(
                              height: 400,
                              child: new ListView.builder(
                                  padding: new EdgeInsets.all(5.0),
                                  itemExtent: 50.0,
                                  itemCount: list.length,
                                  itemBuilder:
                                      (BuildContext context, int index) {
                                    var item = list[index];

                                    return new GestureDetector(
                                      onTap: () {
                                        if (type == 'weight') {
                                          setState(() {
                                            weight = item;
                                          });
                                        }

                                        if (type == 'measure') {
                                          setState(() {
                                            measure = item;
                                          });
                                        }

                                        if (type == 'denom') {
                                          setState(() {
                                            denom = item;
                                          });
                                        }
                                        Navigator.of(context).pop();
                                      },
                                      child: Container(
                                        decoration: BoxDecoration(
                                            border: Border(
                                                bottom: BorderSide(
                                                    color: Utils.hexToColor(
                                                        '#eeeeee')))),
                                        alignment: Alignment.centerLeft,
                                        padding: EdgeInsets.symmetric(
                                            vertical: 5, horizontal: 10),
                                        child: Text(item),
                                      ),
                                    );
                                  }));
                        });
                  },
                  child: Container(
                      width: 510.w,
                      height: 40,
                      child: Container(
                          width: 510.w,
                          height: 40,
                          alignment: Alignment.centerRight,
                          decoration: BoxDecoration(
                            color: Colors.white,
                            border: new Border.all(
                                color: Utils.hexToColor('#D4D4D4'), width: 0.5),
                            borderRadius:
                                new BorderRadius.all(Radius.circular(8.w)),
                          ),
                          child: Padding(
                              padding: EdgeInsets.symmetric(horizontal: 21.w),
                              child: Row(
                                  mainAxisAlignment:
                                      MainAxisAlignment.spaceBetween,
                                  children: <Widget>[
                                    _buildSelectText(title, type),
                                    Image.asset('assets/arrow_botton.png',
                                        width: 22)
                                  ])))))),
        ],
      ),
    );
  }

  _buildSelectText(title, type) {
    Color colorOne = Utils.hexToColor('#333333');
    Color colorTwo = Utils.hexToColor('#C8C8D9');
    double fontSize = 14;

    if (type == 'weight') {
      return Text(weight != '' ? weight : '请选择' + title,
          style: TextStyle(
              color: weight != '' ? colorOne : colorTwo, fontSize: fontSize));
    }

    if (type == 'measure') {
      return Text(measure != '' ? measure : '请选择' + title,
          style: TextStyle(
              color: measure != '' ? colorOne : colorTwo, fontSize: fontSize));
    }

    if (type == 'denom') {
      return Text(denom != '' ? denom : '请选择' + title,
          style: TextStyle(
              color: denom != '' ? colorOne : colorTwo, fontSize: fontSize));
    }
  }

  Widget OrignalValueContainer() {
    return Container(
        padding: EdgeInsets.all(40.w),
        child: Column(
          children: <Widget>[
            _buildInput('物资名称', _nameController),
            _buildSelectInput('物资类型',
                materialTypeName == null ? '请选择物资类型' : materialTypeName),
            _buildInput('物资数量', _numController, true),
            Offstage(
              // offstage: widget.baseApi == 'scrap_enter/' ? false : true,
              offstage: (widget.baseApi == 'scrap_enter/' ||
                      widget.baseApi == 'allocate_enter/')
                  ? false
                  : true,

              child: _buildInput('原值', _originalVauleController, true),
            ),
            _buildInput('规格/型号', _typesController),
            _buildInput('计量单位', _unitController),
            _buildInput('物体重量', _weightController, true),
            _buildSelectBox('重量单位', weightList, context, 'weight'),
            _buildInput('物体长度', _lengthController, true),
            _buildSelectBox('度量单位', measureList, context, 'measure'),
            _buildInput('面额/面值', _denomController, true),
            _buildSelectBox('面额单位', denomList, context, 'denom'),
            _buildDateSelect('有效期'),
            _buildInput('备注', _remarkController, false, 5),
            _buildImageBox('image'),
            _buildImageBox('video'),
          ],
        ));
  }

  @override
  Widget build(BuildContext context) {
    ScreenUtil.init(context, width: 750, height: 1334, allowFontScaling: false);

    return Container(
        width: 700.w,
        height: 1161.w,
        decoration:
            BoxDecoration(borderRadius: BorderRadius.all(Radius.circular(100))),
        child: Column(
          children: <Widget>[
            _buildDialogHead('物资信息'),
            Expanded(
              flex: 1,
              child: SingleChildScrollView(
                child: OrignalValueContainer(),
              ),
            ),
            Container(
              height: 120.w,
              // color: Utils.hexToColor('#FFFFFF'),
              alignment: Alignment.center,
              decoration: BoxDecoration(
                  border: Border(
                      top: BorderSide(
                          width: 1, color: Utils.hexToColor('#F2F2F2')))),
              child: SizedBox(
                width: 620.w,
                height: 76.w,
                child: ElevatedButton(
                  onPressed: () {
                    if (widget.type == 'add') {
                      _addMaterial();
                    }
                    if (widget.type == 'edit') {
                      _editMaterial();
                    }
                  },
                  child: Text(
                    '保存',
                    style: TextStyle(color: Colors.white),
                  ),
                  style: ElevatedButton.styleFrom(
                    backgroundColor: Color(0xFF297CFF),
                    shape: RoundedRectangleBorder(
                        borderRadius: BorderRadius.all(Radius.circular(60.w))),
                  ),
                ),
              ),
            )
          ],
        ));
  }
}
